import CryptoJS from 'crypto-js'
import {apiConfig,version} from "../config";

//DES  ECB模式加密
function encryptStr(message, key) {
  let keyHex = CryptoJS.enc.Utf8.parse(key);
  let encrypted = CryptoJS.DES.encrypt(message, keyHex, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return encrypted.toString();
}

export const decrypt = (message) => {
  let keyHex = CryptoJS.enc.Utf8.parse(apiConfig.app_key);
  let plaintext = CryptoJS.DES.decrypt(message, keyHex, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return plaintext.toString(CryptoJS.enc.Utf8)
};

function requestParams(Params) {
  let addParams = {
    client: version.client,
  };
  let requestParams = mergeJsonObject(addParams, Params);
  return sortObj(requestParams)
}

//按key升序排序
function sortObj(obj) {
  let arr = [];
  for (let key in obj) {
    arr.push(key);
  }
  arr.sort();
  let newObj = {};
  for (let i = 0; i < arr.length; i++) {
    newObj[arr[i]] = obj[arr[i]];
  }
  return newObj;
}

function mergeJsonObject(jsonbject1, jsonbject2) {
  let resultJsonObject = {};
  for (let attr in jsonbject1) {
    resultJsonObject[attr] = jsonbject1[attr];
  }
  for (let attr in jsonbject2) {
    resultJsonObject[attr] = jsonbject2[attr];
  }
  return resultJsonObject;
}


export const getRequestParams = (Params) => {
  let sortAfter = requestParams(Params);
  let base64After = encryptStr(JSON.stringify(sortAfter), apiConfig.app_key);
  let sign = CryptoJS.MD5(base64After + apiConfig.ClientAppKey).toString();
  return {
    sign: sign,
    data: base64After,
    source_id: 'h5'
  }
};

